package org.robot.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

	public static String getMD5(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString().toUpperCase();
	}
	
	/**
	 * 得到整个文件内容的md5值
	 * @param file 文件
	 * @return
	 * @throws Exception
	 */
	public static String md5file(File file) throws Exception {  
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");  
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));  
        byte[] buf = new byte[1024 * 100];  
        int p = 0;  
        while ((p = in.read(buf)) != -1) {  
            messageDigest.update(buf, 0, p);  
        }  
        in.close();  
        byte[] digest = messageDigest.digest();  
        StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < digest.length; i++) {
			if (Integer.toHexString(0xFF & digest[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & digest[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & digest[i]));
		}
		return md5StrBuff.toString().toUpperCase();
    } 
	
	
	
	
	
	
	
	
	
public static void main(String[] args) {
	String s="http://www.sciencedirect.com/science/article/pii/S1076633211005587";
	System.out.println(getMD5(s));
//	String s="<span class=\"WmIJMgMyAzlQOAdi\">鲍</span>陈<span class=\"WmIJMgMyAzZQNQdg\">海</span>海<span class=\"WmIJMgMyAzZQNQdg\">广</span><span class=\"WmIJMgMyAzlQOQdg\">波</span><span class=\"WmIJMgMyAzlQOAdl\">波</span>";
//	System.out.println(s.replaceAll("<span class=\"[^<>]+[mkigu]\">.*?</span>", "").replaceAll("<[^<>]+>", ""));
}
}
